<template>
  <div class="info">
    <div class="face">
      <div class="face-img" @mouseover="handleChangeFace" @mouseout="handleOutFace">
        <img :src="userInfo.avatar" />
        <div class="face-hover" v-show="isFace">
        <img src="@/assets/home/face-hover.png" />
      </div>
      <a-upload
        class="face-btn"
        name="file"
        :multiple="true"
        action="https://e-school.yixuepai100.com/api/common/uploadonline"
        :headers="headers"
        @change="handleChange"
      >
        <a-button></a-button>
      </a-upload>
      </div>
      <span class="text">当前头像</span>
    </div>
    <!-- <a-form-model ref="registerForm" :model="registerForm" :rules="rules"> -->
    <div class="form">
      <div class="register-form">
        <a-form-model
          ref="registerForm"
          :model="registerForm"
          :rules="rules"
          :colon="false"
          :hideRequiredMark="true"
        >
          <a-form-model-item prop="username">
            <a-input
              v-model="registerForm.username"
              autocomplete="off"
              placeholder="姓名"
              @focus="clearValidate('registerForm', 'username')"
            >
              <template slot="prefix">
                <div class="label-prefix">
                  <YxpIcon type="iconlogin_icon_account"></YxpIcon>
                  <span>姓名</span>
                </div>
              </template>
            </a-input>
          </a-form-model-item>
          <a-form-model-item prop="mobile">
            <a-input
              v-model="registerForm.mobile"
              autocomplete="off"
              placeholder="手机号"
              readonly
              disabled
              @focus="clearValidate('registerForm', 'mobile')"
            >
              <template slot="prefix">
                <div class="label-prefix">
                  <YxpIcon type="iconmobile"></YxpIcon>
                  <span>手机号</span>
                </div>
              </template>
            </a-input>
          </a-form-model-item>
          <a-form-model-item class="yxp-form-item" prop="sex">
            <template slot="label">
              <div class="label-prefix">
                <YxpIcon type="iconinformation_icon_sex"></YxpIcon>
                <span>性别</span>
              </div>
            </template>
            <label
              class="yxp-radio-wrap"
              :class="{ 'man-checked': registerForm.sex === 1 }"
            >
              <YxpIcon type="iconzu764"></YxpIcon>
              <input
                disabled
                v-model="registerForm.sex"
                name="sex"
                value="1"
                type="radio"
              />男生
            </label>
            <label
              class="yxp-radio-wrap"
              :class="{ 'girl-checked': registerForm.sex === 2 }"
            >
              <YxpIcon type="iconzu767"></YxpIcon>
              <input
                disabled
                v-model="registerForm.sex"
                value="2"
                name="sex"
                type="radio"
              />女生
            </label>
          </a-form-model-item>
          <a-form-model-item class="yxp-form-item">
            <template slot="label">
              <div class="label-prefix">
                <YxpIcon type="iconinformation_icon_grade"></YxpIcon>
                <span>年级</span>
              </div>
            </template>
            <a-select v-model="registerForm.gradeid" placeholder="点击选择年级" v-show="registerForm.gradeid !== 0">
              <a-select-option
                v-for="item in gradeArr"
                :value="item.grade"
                :key="item.grade"
              >
                {{ item.grade_name }}
              </a-select-option>
            </a-select>
          </a-form-model-item>
          <a-form-model-item prop="school" placeholder="在读学校名称">
            <a-input
              v-model="registerForm.school"
              autocomplete="off"
              placeholder="在读学校名称"
              @focus="clearValidate('registerForm', 'school')"
            >
              <template slot="prefix">
                <div class="label-prefix">
                  <YxpIcon type="iconinformation_icon_school"></YxpIcon>
                  <span>学校</span>
                </div>
              </template>
            </a-input>
          </a-form-model-item>
          <a-form-model-item prop="org_code">
            <a-input
              v-model="registerForm.org_code"
              @change="checkShop"
              autocomplete="off"
              :disabled="orgDisabled"
              placeholder="机构代码"
              @focus="clearValidate('registerForm', 'org_code')"
            >
              <template slot="prefix">
                <div class="label-prefix">
                  <YxpIcon type="iconregister_icon_jigoudaima"></YxpIcon>
                  <span>机构代码</span>
                </div>
              </template>
            </a-input>
            <template v-if="shopError" slot="extra">
              <span class="async-error">
                {{ shopError }}
              </span>
            </template>
          </a-form-model-item>
          <a-form-model-item>
            <a-input v-model="shopName" disabled autocomplete="off">
              <template slot="prefix">
                <div class="label-prefix">
                  <YxpIcon type="iconregister_icon_jigoudaima"></YxpIcon>
                  <span>机构名称</span>
                </div>
              </template>
            </a-input>
          </a-form-model-item>
          <a-button
            type="primary"
            block
            size="large"
            shape="round"
            @click="submitForm"
            >保存</a-button
          >
        </a-form-model>
      </div>
    </div>
    <!-- </a-form-model> -->
  </div>
</template>
<script>
import {
  Modal,
  FormModel,
  Input,
  Checkbox,
  Tabs,
  Select,
  Radio,
  Upload
} from "ant-design-vue";
import { postForm, checkShopCode, fetchGrade, uploadFace } from "@/services";
import { mapState, mapMutations } from "vuex";
import mTypes from "@/store/mutationsTypes";
import { validatePhone, validatePass } from "@/utils/form-validate";
function getBase64(img, callback) {
  const reader = new FileReader();
  reader.addEventListener('load', () => callback(reader.result));
  reader.readAsDataURL(img);
}
export default {
  components: {
    AModal: Modal,
    AFormModel: FormModel,
    AFormModelItem: FormModel.Item,
    AInput: Input,
    ACheckbox: Checkbox,
    ASelect: Select,
    ASelectOption: Select.Option,
    ATabs: Tabs,
    ATabPane: Tabs.TabPane,
    ARadio: Radio,
    ARadioGroup: Radio.Group,
    AUpload: Upload
  },
  data() {
    return {
      shopError: "",
      shopName: "",
      gradeArr: [],
      rules: {
        gradeid: [{ required: true, message: "此项不能为空", trigger: "blur" }],
        // school: [{ required: true, message: "此项不能为空", trigger: "blur" }],
        username: [
          { required: true, message: "此项不能为空", trigger: "blur" }
        ]
        // org_code: [
        //   {
        //     validator: (rule, value, callback) => {
        //       if (!value) {
        //         callback(new Error("请输入机构码"));
        //       } else if (value.length < 8) {
        //         callback(new Error("请输入8位机构码"));
        //       } else {
        //         callback();
        //       }
        //     },
        //     trigger: "blur"
        //   }
        // ]
      },
      registerForm: {
        org_id: 0,
        username: '',
        mobile: '',
        school: '',
        gradeid: 0,
        org_code: '',
        sex: 0
      },
      orgDisabled: true,
      headers: {
        authorization: 'authorization-text'
      },
      isFace: false
    }
  },
  created () {
    let that = this
    postForm('/usercenter/personinfo', {}).then(r => {
      if (r.code == 1) {
        let userInfo = Object.assign({}, r.data, that.userInfo)
        window.localStorage.setItem('oldPhone', r.data.mobile)
        that[mTypes.userInfo](userInfo)
        that.userInfo.sex = Number(that.userInfo.sex) || 0
        that.registerForm = Object.assign(
          {},
          that.registerForm,
          that.mapByListKey(Object.keys(that.registerForm), that.userInfo)
        );
        if (that.userInfo.org) {
          if (that.userInfo.org.code === '') {
            that.orgDisabled = false
          }
          that.registerForm.org_code = that.userInfo.org.code
          that.shopName = that.userInfo.org.nickname
        }
      }
    });
    fetchGrade().then(res => {
      if (res.code === 1) {
        this.gradeArr = res.data;
      }
    });
  },
  computed: {
    ...mapState({
      userInfo: state => state.userInfo
    })
  },
  mounted() {},
  methods: {
    ...mapMutations([mTypes.userInfo]),
    mapByListKey(lkey, mapv) {
      let m = {};
      for (let k of lkey) {
        typeof mapv[k] !== "undefined" && (m[k] = mapv[k]);
      }
      return m;
    },
    clearValidate(form, filed) {
      this.$refs[form].clearValidate(filed);
    },
    submitForm() {
      this.$refs.registerForm.validate(async valid => {
        if (valid) {
          let { username, gradeid, school } = this.registerForm
          let params = {
            username,
            gradeid,
            school
          }
          if (!this.orgDisabled) {
            params.org_code = this.registerForm.org_code
          }
          let res = await postForm("/usercenter/submitinfo", {
            ...params
          });
          if (res.code === 1) {
            this.$message.success("保存成功");
            this[mTypes.userInfo](
              Object.assign({}, this.userInfo, this.registerForm)
            );
          }
        }
      });
    },
    checkShop(e) {
      if (e.target.value.length === 8) {
        checkShopCode({ shop_code: e.target.value }).then(res => {
          if (res.code === 1) {
            this.shopName = res.data.org_name;
            res.data.org_id && (this.registerForm.org_id = res.data.org_id)
            this.shopError = "";
          } else {
            this.shopName = "";
            this.shopError = "机构代码不正确";
          }
        });
      }
    },
    handleChangeSex(type) {
      return false;
      if (type === 1) {
        this.registerForm.sex = this.registerForm.sex === 0 ? 1 : 0;
      } else {
        this.registerForm.sex = this.registerForm.sex === 0 ? 2 : 0;
      }
    },
    handleChange (info) {
      if (info.file.status !== 'uploading') {
        console.log(info.file, info.fileList)
      }
      if (info.file.status === 'done') {
        getBase64(info.file.originFileObj, imageUrl => {
          this.userInfo.avatar = imageUrl
        })
        this.$message.success('头像上传成功')
      } else if (info.file.status === 'error') {
        this.$message.error('头像上传失败')
      }
    },
    handleChangeFace () {
      console.log(444)
      this.isFace = true
    },
    handleOutFace () {
      this.isFace = false
    }
  }
};
</script>
<style lang="less" scoped>
.register-form {
  /deep/ .ant-form-extra {
    & /deep/ .async-error {
      color: #ff4500;
    }
  }
  /deep/ .ant-form-explain {
    text-align: left;
  }
}
.ant-form-item {
  .label-prefix {
    width: 90px;
    text-align: left;
  }
}

.info {
  width: 412px;
  text-align: center;
  margin: 30px auto;
  .face {
    position:relative;
    .face-img {
      width: 60px;
      height: 60px;
      border-radius: 30px;
      cursor: pointer;
      overflow: hidden;
      margin: 0 auto;
      img {
        width: 100%;
        height: 100%;
      }
    }
    .face-hover {
      position: absolute;
      left: 50%;
      top: 0;
      transform: translateX(-50%);
      width: 60px;
      height: 60px;
      background: rgba(0,0,0,.5);
      border-radius: 30px;
      z-index:3;
      img {
        width: 22px;
        height: 22px;
        margin-top: 18px;
      }
    }
    .text {
      display: block;
      font-size: 16px;
      font-family: Microsoft YaHei;
      font-weight: 400;
      line-height: 21px;
      color: #1c1c1c;
      margin-top: 10px;
    }
    .file {
      position: absolute;
      left: 50%;
      top: 0;
      transform: translateX(-50%);
      display: block;
      width: 60px;
      height: 60px;
      opacity: 0;
      z-index: 10;
    }
  }
  .form {
    &-item {
      display: flex;
      align-items: center;
      height: 34px;
      text-align: left;
      border-bottom: 1px solid #e0e0e0;
      padding: 0 20px;
      margin-top: 25px;
      span {
        display: block;
        width: 68px;
        font-size: 16px;
        font-family: Microsoft YaHei;
        font-weight: 400;
        color: #24272b;
        margin-right: 15px;
      }
      input {
        width: 280px;
        line-height: 30px;
        border: none;
        outline: none;
        &:focus {
          border: none;
          outline: none;
        }
        &::-webkit-input-placeholder {
          color: #bfbfbf;
        }
      }
      .sex {
        display: flex;
        align-items: center;
        &-item {
          margin-right: 29px;
          cursor: pointer;
          img {
            width: 16px;
            height: 16px;
            margin-right: 10px;
          }
          &:last-child {
            margin-right: 0;
          }
        }
      }
      &:last-child {
        margin-bottom: 0;
      }
    }
    & /deep/ .ant-input-disabled {
      background-color: transparent;
      color: #000;
      font-weight: bold;
    }
    .yxp-form-item {
      display: flex;
      border-bottom: 1px solid #e0e0e0; /* no */
      & /deep/ .ant-form-item-control-wrapper {
        display: flex;
        justify-content: flex-start;
        align-items: center;
        flex: 1;
      }
      /deep/ .ant-select-selection {
        min-width: 120px;
        border: none;
        display: flex;
        justify-content: center;
      }
      /deep/ .ant-select-focused .ant-select-selection,
      .ant-select-selection:focus,
      .ant-select-selection:active {
        box-shadow: none;
      }

      /deep/ .ant-select-arrow {
        position: relative;
        color: #000;
      }

      /deep/ .ant-form-item-no-colon {
        display: flex;
        align-items: center;
        color: rgba(0, 0, 0, 0.65);
        .anticon {
          margin-right: 6px; /* no */
        }
      }

      .yxp-radio-wrap {
        display: flex;
        align-items: center;
        &:nth-child(1) {
          margin-right: 30px;
        }
        &.man-checked {
          color: #5ca2ff;
        }
        &.girl-checked {
          color: #ff719d;
        }

        .anticon {
          padding: 0 10px;
        }
        input {
          display: none;
        }
      }
    }
  }
  .btn {
    width: 360px;
    height: 50px;
    line-height: 50px;
    font-size: 16px;
    font-family: Microsoft YaHei;
    font-weight: bold;
    color: #ffffff;
    text-align: center;
    background: linear-gradient(180deg, #13c998 0%, #27bfa3 100%);
    box-shadow: 0px 3px 6px rgba(23, 178, 145, 0.4);
    border-radius: 25px;
    margin: 45px auto 0;
  }
}
.face-btn {
  display: block;
  position: absolute;
  left: 50%;
  top: 0;
  transform: translateX(-50%);
  width: 60px;
  height: 60px;
  z-index: 100;
  /deep/.ant-upload {
    width: 60px;
    height: 60px;
    border: none;
    opacity: 0;
    .ant-btn {
      width: 60px;
      height: 60px;
    }
  }
  /deep/.ant-upload-list {
    display: none;
  }
}
/deep/.ant-form-item .label-prefix {
  width: 100px !important;
}
</style>
